#include "player_widget.hpp"
#include <QDateTime>
PlayerWidget::PlayerWidget(QWidget *parent)
    : QWidget(parent)
    , mainLayout(nullptr)
    , titleLabel(nullptr)
    , configLabel(nullptr)
    , rosStatusLabel(nullptr)
    , nh(nullptr)
    , rosTimer(nullptr)
    , rosConnected(false)
{
    setupUI();
    setupROS();
}
PlayerWidget::~PlayerWidget()
{
    if (nh) {
        delete nh;
    }
}
void PlayerWidget::setupUI()
{
    mainLayout = new QVBoxLayout(this);
    titleLabel = new QLabel("Player Control Tab (ROS1 Enabled)", this);
    titleLabel->setStyleSheet("font-size: 18px; font-weight: bold; color: green;");
    titleLabel->setAlignment(Qt::AlignCenter);
    configLabel = new QLabel(QString("Config Info:\n"
        "App Name: %1\n"
        "Command Topic: %2\n"
        "Image Topic: %3\n"
        "Queue Size: %4\n"
        "Timer Interval: %5ms")
        .arg(Config::APP_NAME)
        .arg(Config::PLAYER_COMMAND_TOPIC)
        .arg(Config::PLAYER_IMAGE_TOPIC)
        .arg(Config::PLAYER_QUEUE_SIZE)
        .arg(Config::PLAYER_ROS_TIMER_INTERVAL), this);
    configLabel->setStyleSheet("background-color: #f0f0f0; padding: 10px; border: 1px solid #ccc;");
    rosStatusLabel = new QLabel("ROS Status: Initializing...", this);
    rosStatusLabel->setStyleSheet("font-weight: bold; padding: 5px;");
    mainLayout->addWidget(titleLabel);
    mainLayout->addWidget(configLabel);
    mainLayout->addWidget(rosStatusLabel);
    mainLayout->addStretch();
}
void PlayerWidget::setupROS()
{
    try {
        nh = new ros::NodeHandle();
        commandPub = nh->advertise<std_msgs::String>(Config::PLAYER_COMMAND_TOPIC.toStdString(), 
            Config::PLAYER_QUEUE_SIZE);
        rosConnected = true;
        rosStatusLabel->setText("ROS Status: Connected");
        rosStatusLabel->setStyleSheet("color: green; font-weight: bold; padding: 5px;");
        rosTimer = new QTimer(this);
        connect(rosTimer, &QTimer::timeout, this, &PlayerWidget::updateROS);
        rosTimer->start(Config::PLAYER_ROS_TIMER_INTERVAL);
    } catch (const std::exception& e) {
        rosConnected = false;
        rosStatusLabel->setText(QString("ROS Status: Connection Failed - %1").arg(e.what()));
        rosStatusLabel->setStyleSheet("color: red; font-weight: bold; padding: 5px;");
    }
}
void PlayerWidget::updateROS()
{
    if (rosConnected && ros::ok()) {
        ros::spinOnce();
        static int counter = 0;
        counter++;
        if (counter % 50 == 0) {
            std_msgs::String msg;
            msg.data = QString("test_message_%1").arg(QDateTime::currentDateTime().toString(Config::LOG_TIME_FORMAT)).toStdString();
            commandPub.publish(msg);
        }
    } else if (rosConnected) {
        rosConnected = false;
        rosStatusLabel->setText("ROS Status: Disconnected");
        rosStatusLabel->setStyleSheet("color: red; font-weight: bold; padding: 5px;");
    }
}